package com.mm.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CacheComponent {
    @Autowired
    protected RedisTemplate redisTemplate;

    /**
     * 添加数据对象到缓存
     */
    public void putForExpire(String key, Object value, long timeout) {
        BoundValueOperations<String, Object> boundValueOperations = redisTemplate.boundValueOps(key);
        boundValueOperations.set(value, timeout, TimeUnit.SECONDS);
    }

    /**
     * 取通过 putForExpire方法添加的缓存值
     */
    public Object getForExpire(String key) {
        return redisTemplate.boundValueOps(key).get();
    }

    /**
     * 删除通过 putForExpire方法添加的缓存值
     */
    public void removeForExpire(String key) {
        redisTemplate.delete(key);
    }
}
